﻿;
(function ($) {
    var defaults = {
        redirectToProfilePage: false,
        maxSuggetions: 10,
        mySiteUrl: "",
        showpicture: true,
        showInitials: false,
        showSearchSuggetions: true,
        principalType: 1
    };
    var showResults = true;

    $.searchPeople = function (options) {
        try {
            if (eval($('#SearchBox input').parent().css("width").replace("px", "")) < 300) {
                $('#SearchBox input').parent().css("width", "300px")
                if ($('#SearchBox .ms-srch-sb-navImg').length == 0) {
                    $('#SearchBox input').css("width", "270px");
                } else {
                    $('#SearchBox input').css("width", "250px");
                }
                $('#SearchBox input').css("height", "20px");
                if ($('.ms-mpSearchBox').length != 0) {
                    $('.ms-mpSearchBox').css("width", "300px");
                }
            }
        } catch (ex) { }
        $('.ms-srch-sb-navLink').click(function () {
            $('.ms-qSuggest-container').css("top", "").css("left", "");
        });

        options = $.extend({}, defaults, options);

        var data;
        var isFirstItem = true;

        $.extend($.ui.autocomplete.prototype, {
            _renderItem: function (ul, item) {
                var term = this.element.val(),
                    regex = new RegExp('(' + term + ')', 'gi');
                html = item.label.replace(regex, "<b>$&</b>");
                if (item.email != null) {
                    var emptyLi = "<li></li>";

                    if (item["addEmpty"] == "true" && !isFirstItem) {
                        emptyLi = "style = 'border-top:1px solid #0F7CD1'";

                    } else {
                        emptyLi = "";
                    }
                    if (options.showpicture) {
                        var actualUrl = options.mySiteUrl + '/_layouts/15/userphoto.aspx?accountname=' + item["networkaddress"] + '&amp;size=S\&';
                        var picUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@accountName)?@accountName='" + item["networkaddress"] + "'&$select=PictureUrl,UserProfileProperties";
                        return $("<li " + emptyLi + "><div class='userSuggestion'><span class='ms-imnSpan'><a onmouseover='IMNShowOOUI();' onmouseout='IMNHideOOUI()' style='padding: 0px;'><div class='ms-tableCell userImageContainer'><span class='ms-imnlink ms-spimn-presenceLink'><span class='ms-spimn-presenceWrapper ms-spimn-imgSize-5x36'><img name='imnmark' title='' showofflinepawn='1' class='ms-spimn-img ms-spimn-presence-offline-5x36x32' src='/_layouts/15/images/spimn.png' sip='" + item["sip"] + "' id='imn_" + item["email"] + ",type=sip' /></span></span><img class='userIMG' id='img_" + item["networkaddress"].replace('\\', '_') + "' src='" + actualUrl + "' userName='" + item.label + "' UserImgUrl=\"" + picUrl + "\" alt='" + item["value"] + "'/></div><div class='userDetails ms-verticalAlignTop ms-tableCell'><div class='contactName'>" + html + "</div><div class='contactTitle'>" + item["title"] + "</div></div></a></span></div></li>")
                            .appendTo(ul);
                    } else {
                        return $("<li  " + emptyLi + "><div class='userSuggestion'><span class='ms-imnSpan'><a onmouseover='IMNShowOOUI();' onmouseout='IMNHideOOUI()'  href='#' class='ms-imnlink ms-spimn-presenceLink' ><span class='ms-spimn-presenceWrapper ms-imnImg ms-spimn-imgSize-10x10'><img name='imnmark' title='' ShowOfflinePawn='1' class='ms-spimn-img ms-spimn-presence-offline-10x10x32' src='/_layouts/15/images/spimn.png?rev=23' alt='User Presence' sip='" + item["sip"] + "' id='imn_" + item["email"] + ",type=sip' /></span>" + item["value"] + "</a></span></div></li>")
                            .appendTo(ul);
                    }
                } else {
                    if (item["suggestionLink"] == "true") {
                        isFirstItem = false;
                        return $("<li><a class='searchLink' href='javascript: {}'>" + html + "</a></li>").appendTo(ul);
                    } else {
                        return $("<li>" + item.label + "</li>").appendTo(ul);
                    }
                }
            }
        });

        RegisterSod("autofill.js", "/_layouts/15/autofill.js");

        $("#SearchBox input").autocomplete({
            source: function (request, response) {
                $('#SearchBox .ms-qSuggest-container').css("top", "-500px").css("left", "-500px").css("display", "none");
                if (options.showpicture) {
                    $('.picSpinner').remove();
                }
                isFirstItem = true;

                EnsureScript('SP.js', typeof SP.ClientContext, function () {
                    EnsureScript('autofill.js', typeof SPClientAutoFill, function () {
                        var query = new SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters();
                        query.set_allowMultipleEntities(true);
                        query.set_maximumEntitySuggestions(options.maxSuggetions);
                        query.set_allowEmailAddresses(true);
                        query.set_principalType(options.principalType);
                        query.set_principalSource(15);
                        query.set_queryString($('#SearchBox input').val());
                        var clientContext = SP.ClientContext.get_current();
                        var searchResult = SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser(clientContext, query);

                        clientContext.executeQueryAsync(function () {
                            var newData = [];
                            var addEmpty = "false";

                            if (options.showSearchSuggetions) {

                                addEmpty = "true";
                                var searchRestSource = _spPageContextInfo.webAbsoluteUrl + "/_api/search/suggest?querytext='" + $('#SearchBox input').val() + "'" + "&fPreQuerySuggestions=true&iNumberOfResultSuggestions=5&fHitHighlighting=false";
                                $.ajax({
                                    url: searchRestSource,
                                    method: "GET",
                                    async: false,
                                    headers: {
                                        "accept": "application/json; odata=verbose",
                                    },
                                    success: function (data) {
                                        var suggestResults = data.d.suggest.Queries.results;
                                        if (suggestResults.length != 0) {
                                            for (var i = 0; i < suggestResults.length; i++) {
                                                newData.push({
                                                    value: suggestResults[i].Query,
                                                    suggestionLink: "true"
                                                });
                                            }
                                        }
                                    },
                                    error: function (err) {
                                        //alert(JSON.stringify(err));
                                    },
                                });
                            }
                            var results = clientContext.parseObjectFromJsonString(searchResult.get_value());

                            for (i = 0; i < results.length; i++) {
                                var filtered = $(newData).filter(function () {
                                    return this.value == results[i].DisplayText;
                                });
                                if (filtered.length == 0) {
                                    var title = results[i].EntityData.Title;
                                    if (title == undefined) {
                                        title = "";
                                    }
                                    var sip = results[i].EntityData.SIPAddress;
                                    if (sip == undefined) {
                                        sip = results[i].EntityData.Email;
                                    }

                                    newData.push({
                                        value: results[i].DisplayText,
                                        id: results[i].Key,
                                        email: results[i].EntityData.Email,
                                        networkaddress: results[i].Description,
                                        title: title,
                                        sip: sip,
                                        addEmpty: addEmpty
                                    });
                                    addEmpty = "false";
                                }
                            }

                            data = newData.slice();

                            //response($.ui.autocomplete.filter(newData, request.term));
                            response(newData);
                        });
                    });
                });
            },
            select: function (event, ui) {
                if (options.redirectToProfilePage) {
                    if (ui.item.networkaddress != null) {
                        SP.Utilities.HttpUtility.navigateTo(options.mySiteUrl + '/Person.aspx?accountname=' + ui.item.networkaddress);
                    } else {
                        var searchID = $('#SearchBox').parent().attr('id');
                        EnsureScriptFunc('Search.ClientControls.js', 'Srch.U', function () {
                            $find(searchID).search($('#SearchBox input').val());
                        });
                    }
                } else {
                    var searchID = $('#SearchBox').parent().attr('id');
                    EnsureScriptFunc('Search.ClientControls.js', 'Srch.U', function () {
                        $find(searchID).search(ui.item.label);
                    });
                }
            },
            search: function (event, ui) {
                $(this).addClass('loader');
            },
            response: function (event, ui) {
                if (options.redirectToProfilePage) {
                    if (ui.content.length != 0) {
                        var encodeSearch = encodeURIComponent($('#SearchBox input').val());
                        ui.content.push({
                            label: "<a class='searchLink searchForLink' href='javascript: {}'>Search for \"<i>" + $('#SearchBox input').val() + "</i>\"</a>",
                            id: "SearchLink",
                            button: true
                        });
                    } else {
                        $(this).removeClass('loader');
                    }
                }

            },
            appendTo: "#SearchBox",
            open: function () {
                $(this).removeClass('loader');
                if (options.showInitials && options.showpicture) {
                    if ($.support.html5Clone) {
                        loadUserPicture();
                    }
                }
                if (showResults) {
                    $('#SearchBox .ui-autocomplete').removeClass("ui-corner-all").addClass("ms-clear");
                    $('#SearchBox .ui-autocomplete').css("width", $('#SearchBox input').parent().css("width"));
                    $('#SearchBox .ui-menu-item').css('list-style-image', "none");
                    $('#SearchBox .ui-autocomplete').css("top", (eval($(this).position().top)) + eval($(this).css("height").replace("px", "")) + 2 + "px");
                    $('#SearchBox .ui-autocomplete').css("left", ($('.ui-autocomplete').position().left - eval($(this).css("margin-left").replace("px", "")) - 1) + "px");
                    $('#SearchBox .ui-autocomplete .searchForLink').parent().css("border-top", "1px solid #0F7CD1");
                    ProcessImn();
                    if (options.showpicture) {
                        $("#SearchBox .userIMG").imgPreload({
                            spinner_src: '/_layouts/15/Aray.SearchUser/spinner.gif'
                        });
                    }
                } else {
                    $('#SearchBox .ui-autocomplete').hide();
                    showResults = true;
                }
            }
        });
        $("#SearchBox input").keypress(function (e) {
            if (e.keyCode == 13 && options.redirectToProfilePage) {
                $('#SearchBox .ui-autocomplete').hide();
                showResults = false;
            }
        });

        function GenerateInitialImageForUser(img, name, id) {

            var colors = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"];

            nameSplit = name.split(" "),
                initials = nameSplit[0].charAt(0).toUpperCase() + nameSplit[1].charAt(0).toUpperCase();
            initials = initials.split('').reverse().join('');
            var charIndex = initials.charCodeAt(0) - 65,
                colourIndex = charIndex % 19;

            img.parent().append('<canvas style="margin-right:10px;" id="cnv' + id + '" width="36" height="36"></canvas>');
            var canvas = document.getElementById('cnv' + id);
            var context = canvas.getContext("2d");

            var canvasWidth = $(canvas).attr("width"),
                canvasHeight = $(canvas).attr("height"),
                canvasCssWidth = canvasWidth,
                canvasCssHeight = canvasHeight;

            if (window.devicePixelRatio) {
                $(canvas).attr("width", canvasWidth * window.devicePixelRatio);
                $(canvas).attr("height", canvasHeight * window.devicePixelRatio);
                $(canvas).css("width", canvasCssWidth);
                $(canvas).css("height", canvasCssHeight);
                context.scale(window.devicePixelRatio, window.devicePixelRatio);
            }

            context.fillStyle = colors[colourIndex];
            context.fillRect(0, 0, canvas.width, canvas.height);
            context.font = "16px Arial";
            context.textAlign = "center";
            context.fillStyle = "#FFF";
            context.fillText(initials, canvasCssWidth / 2, canvasCssHeight / 1.5);
            img.remove();
        }


        function loadUserPicture() {
            $('#SearchBox .userIMG').each(function () {
                var userImg = $(this);
                $.ajax({
                    url: $(this).attr("UserImgUrl"),
                    type: "GET",
                    headers: {
                        "accept": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val()
                    },
                    success: function (data) {
                        var picUrl = data.d.PictureUrl;
                        if (!picUrl) {
                            GenerateInitialImageForUser(userImg, userImg.attr("userName"), userImg.attr("id"));
                        }
                    }
                });
            });
        }

    }
})(jQuery);


$(document).ready(function () {
    _spBodyOnLoadFunctionNames.push("addSearchBox");
    setTimeout(addSearchBox, 1500);
});

function addSearchBox() {
    // TODO: update My Site Url
    var settings = {
        mySiteUrl: "MY_SITE_URL",
        redirectToProfilePage: true,
        maxSuggetions: 10,
        showpicture: false,
        showInitials: true,
        principleType: 1,
        showSearchSuggetions: true
    }
    $.searchPeople(settings);
}